package com.agriculture.controller;

import com.agriculture.common.CouponStatus;
import com.agriculture.common.R;
import com.agriculture.entity.User;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.agriculture.entity.ViewCoupon;
import com.agriculture.service.ViewCouponService;
import com.agriculture.utils.JwtUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@Slf4j
@CrossOrigin
@RequestMapping("/viewusercoupon")
public class ViewCouponContorller {

    @Autowired
    private ViewCouponService viewUserCouponService;

    /**
     * 根据 id 返回登录用户所有优惠券信息
     * 收藏了，还没过期，还没用
     * @param token
     * @return
     */
    @GetMapping("/getAll/{token}")
    public R<List<ViewCoupon>> getCouponById(@PathVariable String token){
        User user = JwtUtils.parseToken(token);
        Long id = user.getId();
        LambdaQueryWrapper<ViewCoupon> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ViewCoupon::getUserId, id);
        queryWrapper.eq(ViewCoupon::getIsDeleted, CouponStatus.UNDELETED);
        queryWrapper.ge(ViewCoupon::getExpirationTime, LocalDateTime.now());
        queryWrapper.le(ViewCoupon::getEffectiveTime, LocalDateTime.now());
        return R.success(viewUserCouponService.list(queryWrapper));
    }

    /**
     * 返回当前登录用户的所有已过期优惠券
     * 收藏了，未使用，已过期
     * @param token
     * @return
     */
    @GetMapping("/getdelAll/{token}")
    public R<List<ViewCoupon>> getDelCouponById(@PathVariable String token){
        User user = JwtUtils.parseToken(token);
        Long id = user.getId();
        LambdaQueryWrapper<ViewCoupon> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ViewCoupon::getUserId, id);
        queryWrapper.eq(ViewCoupon::getIsDeleted, CouponStatus.UNDELETED);
        queryWrapper.le(ViewCoupon::getExpirationTime, LocalDateTime.now());
        return R.success(viewUserCouponService.list(queryWrapper));
    }


    /**
     * 查询所有 view_coupon
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize){

        LambdaQueryWrapper<ViewCoupon> queryWrapper = new LambdaQueryWrapper<>();

        //分页构造器
        Page<ViewCoupon> pageInfo = new Page<>(page,pageSize);

        //添加排序条件，根据Level进行排序
        queryWrapper.orderByAsc(ViewCoupon::getExpirationTime);

        //分页查询
        Page<ViewCoupon> ViewOrderPage = viewUserCouponService.page(pageInfo, queryWrapper);
        return R.success(ViewOrderPage);
    }
}










